import Vue from "vue";
import Vuex from "vuex";

//配置vuex做全局登录状态管理
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		isLogin: JSON.parse(sessionStorage.getItem("isLogin")) || JSON.parse(localStorage.getItem("isLogin")) || false,
		userInfo: JSON.parse(sessionStorage.getItem("userInfo")) || JSON.parse(localStorage.getItem("userInfo")) || {},
		follows: JSON.parse(sessionStorage.getItem("follows")) || JSON.parse(localStorage.getItem("follows")) || [],
    token: sessionStorage.getItem("token") || localStorage.getItem("token") || "",
	},
	mutations: {
		login(state, payload) {
			state.isLogin = true;
			state.userInfo = payload.userInfo;
			state.follows = payload.follows;
      state.token = payload.token;
			if (payload.remember) {
				localStorage.setItem("isLogin", true);
				localStorage.setItem("userInfo", JSON.stringify(payload.userInfo));
				localStorage.setItem("follows", JSON.stringify(payload.follows));
        localStorage.setItem("token", payload.token);
			}
      sessionStorage.setItem("isLogin", true);
      sessionStorage.setItem("userInfo", JSON.stringify(payload.userInfo));
			sessionStorage.setItem("follows", JSON.stringify(payload.follows));
      sessionStorage.setItem("token", payload.token);
		},
		logout(state) {
			state.isLogin = false;
			state.userInfo = {};
			state.follows = [];
      state.token = "";
			localStorage.removeItem("isLogin");
      localStorage.removeItem("userInfo");
			localStorage.removeItem("follows");
      localStorage.removeItem("token");
      sessionStorage.removeItem("isLogin");
      sessionStorage.removeItem("userInfo");
			sessionStorage.removeItem("follows");
      sessionStorage.removeItem("token");
		},
		update(state, payload) {
			state.userInfo[payload.key] = payload.value;
			if (localStorage.getItem("userInfo")) {
				localStorage.setItem("userInfo", JSON.stringify(state.userInfo));
			}
			sessionStorage.setItem("userInfo", JSON.stringify(state.userInfo));
		},
		follow(state, payload) {
			state.follows.push(payload);
			if (localStorage.getItem("follows")) {
				localStorage.setItem("follows", JSON.stringify(state.follows));
			}
			sessionStorage.setItem("follows", JSON.stringify(state.follows));
		},
		unfollow(state, payload) {
			state.follows = state.follows.filter(item => item !== payload);
			if (localStorage.getItem("follows")) {
				localStorage.setItem("follows", JSON.stringify(state.follows));
			}
			sessionStorage.setItem("follows", JSON.stringify(state.follows));
		}
	},
});

export default store;
